import java.util.Random;


public class BruteForce {
	/**
	 * Smart Exhaustive search method
	 * Called By Game
	 * Uses Randomized search algorithm
	 * 
	 * @author Casey Huckins
	 * @modified Larry Savago
	 * @date 4/13/2012
	 */
	
	Board board;
	private int counter;
	private Square[] ideal;
	public int search(Board mboard, Ship ship){
		board = mboard;
		ideal = mboard.getIdeal();
		int direction = 0;
		counter = 0;
		int row = 0;
		int col = 0;
		int search = 0;
		
		// randomize the selection of the ideal array
		 int arraySize = 27;
		 int[] x = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
		 int[] y = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
		 
		 Random randomGenerator =new Random(); 
		 for (int r =0; r<x.length; r++) {
			 int randomInt = randomGenerator.nextInt(arraySize); //gets a random number between 0-27 then gets smaller 
			 search = x[randomInt];
			 counter++;
			 if (ship.search(ideal[search])){
					row = ideal[search].getId()[0];
					col = ideal[search].getId()[1];
					break;
			 }
			 System.arraycopy(x, randomInt + 1, y, randomInt, (x.length-1)-randomInt);
			 y[arraySize-1] = -1;
			 x = y;
			 arraySize--;
			 

		 }

//		for (int i = 0; i < ideal.length; i++) {
//			counter ++;
//			if (ship.search(ideal[i])){
//				row = ideal[i].getId()[0];
//				col = ideal[i].getId()[1];
//				break;
//			}
//		}

		int hits = 1;
		
		for (int i = 1; hits<3; i++) {
			//left
			if ((direction == 0||direction == 1) && col>=i && check(ship,row,col-i)) {
				hits++;
				direction = 1;
			}
			else if (direction == 1 && hits>1) {
				direction = 2;
				i = 0;
			}
			// checkRight()
			if ((direction == 0||direction == 2) && col<Board.COLS-i && check(ship,row,col+i)) {
				hits++;
				direction = 2;
			}
			else if (direction == 2 && hits>1) {
				direction = 1;
				i = 0;
			}
			
			// checkTop()
			if ((direction == 0||direction == 3) && row>=i && check(ship,row - i ,col)) {
				hits++;
				direction = 3;

			}
			else if (direction == 3 && hits>1) {
				direction = 4;
				i = 0;
			}
			// checkBottom()
			if ((direction == 0||direction == 4) && row<Board.ROWS-i && check(ship,row + i ,col)) {
				hits++;
				direction = 4;
			}
			else if (direction == 4 && hits>1) {
				direction = 3;
				i = 0;
			}
		}
			System.out.println("" + counter);
			//System.out.println("" + direction);

		return counter;
	}
	
	public boolean check(Ship ship, int row, int col) {
		counter++;
		//System.out.println("ID = " + board.getSquare(row, col).getId()[0] + "," + board.getSquare(row, col).getId()[1] );
		//System.out.println(board.getSquare(row, col).toString());
		if (ship.search(board.getSquare(row, col))) {
			return true;
		}
		return false;
	}
	
}
